﻿using System;
using System.Windows.Forms;
using Bewise.SmartIndexManager.Core.Classes.Types;
using Bewise.SmartIndexManager.Core.Classes.Database;
using Bewise.SmartIndexManager.Core;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Bewise.SmartIndexManager.UI.Forms
{
    public partial class SelectObjectForm : Form
    {
        private TaskInfosContainer _parentObjectContainer;
        private string _connectionString;

        public SelectObjectForm()
        {
            InitializeComponent();

            TypeOfObjects = new TypeOfObjects();

            radioButtonAllDatabases.Tag = DatabasesTypeEnum.AllDatabase;
            radioButtonAllUserDatabases.Tag = DatabasesTypeEnum.AllUserDatabases;
            radioButtonSystemeDatabases.Tag = DatabasesTypeEnum.SystemDatabase;
            radioButtonTheseDatabases.Tag = DatabasesTypeEnum.TheseDatabases;

            radioButtonAllDatabases.CheckedChanged += radioButtonSelectedObjectChange;
            radioButtonAllUserDatabases.CheckedChanged += radioButtonSelectedObjectChange;
            radioButtonSystemeDatabases.CheckedChanged += radioButtonSelectedObjectChange;
            radioButtonTheseDatabases.CheckedChanged += radioButtonSelectedObjectChange;
        }

        public TaskInfosContainer ParentObjectContainer
        {
            private get { return _parentObjectContainer; }
            set
            {
                _parentObjectContainer = value;
                _connectionString = _parentObjectContainer.ConnectionString;
                TypeOfObjects.DatabasesTypeEnum = _parentObjectContainer.InstanceInfos.SelectedDatabases;

                switch (TypeOfObjects.DatabasesTypeEnum)
                {
                    case DatabasesTypeEnum.AllDatabase:
                        radioButtonAllDatabases.Checked = true;
                        break;
                    case DatabasesTypeEnum.SystemDatabase:
                        radioButtonSystemeDatabases.Checked = true;
                        break;
                    case DatabasesTypeEnum.AllUserDatabases:
                        radioButtonAllUserDatabases.Checked = true;
                        break;
                    case DatabasesTypeEnum.TheseDatabases:
                        radioButtonTheseDatabases.Checked = true;
                        break;
                }
            }
        }

        private TypeOfObjects TypeOfObjects { get; set; }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            ParentObjectContainer.SelectedDatabases = TypeOfObjects.DatabasesTypeEnum;
            ParentObjectContainer.InstanceInfos.Databases.Clear();

            if (ParentObjectContainer.SelectedDatabases == DatabasesTypeEnum.TheseDatabases)
            {
                foreach (var selectedDatabase in checkedListBoxDatabases.CheckedItems)
                    ParentObjectContainer.InstanceInfos.Databases.Add(new DatabaseInfos() { DatabaseName = selectedDatabase.ToString() });
            }

            Close();
        }

        private void radioButtonSelectedObjectChange(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
                TypeOfObjects.DatabasesTypeEnum = ((DatabasesTypeEnum)((RadioButton)sender).Tag);

            if (TypeOfObjects.DatabasesTypeEnum == DatabasesTypeEnum.TheseDatabases && this.checkedListBoxDatabases.Items.Count == 0)
                InitComboInitialCatalog(_connectionString);
        }

        private void InitComboInitialCatalog(string connectionManager)
        {
            try
            {
                // récupération des base de données associées connectionManager
                this.checkedListBoxDatabases.DataSource = GetDatabasesFromConnectionString(connectionManager);

                for (int index = 0; index < this.checkedListBoxDatabases.Items.Count; index++)
                {
                    var isDbChecked =
                        _parentObjectContainer.InstanceInfos.Databases.Where(
                            item => item.DatabaseName == checkedListBoxDatabases.Items[index].ToString()).FirstOrDefault();
                    // check des base de données selectionnées
                    if (isDbChecked != null)
                        checkedListBoxDatabases.SetItemCheckState(index, CheckState.Checked);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Error occurs during ComboInitialCalog populating");
            }
        }

        private List<string> GetDatabasesFromConnectionString(string connectionString)
        {
            var listDatabases = new List<string>();
            try
            {
                SqlConnection conn = new SqlConnection(connectionString);
                ServerConnection serverConnection = new ServerConnection(conn);
                Server server = new Server(serverConnection);


                

                // récupération de toutes les base de données de currentConnectionManager
                foreach (Database database in server.Databases)
                    listDatabases.Add(database.Name);
            }
            catch (Exception)
            {
                throw;
            }
            return listDatabases;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}